<?php
/**
 * RequirementDerivation repository
 */
namespace BWL\webshopBundle\Repository;

use Doctrine\ORM\EntityRepository;
use BWL\webshopBundle\Entity\Assignment;
use BWL\webshopBundle\Entity\Requirement;

/**
 * RequirementDerivationRepository
 *
 * RequirementDerivation specific methods to locale entity.
 */
class RequirementDerivationRepository extends EntityRepository
{

  /**
   * Return one Derivation by the id objects.
   * @param \BWL\webshopBundle\Entity\Assignment $assignment
   * @param \BWL\webshopBundle\Entity\Requirement $requirement
   * @return object
   */
  public function findByIds(Assignment $assignment, Requirement $requirement) {
    return $this->findOneBy(array('assignment' => $assignment, 'requirement' => $requirement));
  }

  /**
   * Find requirement derivations in period
   * @param \DateTime $from
   * @param \DateTime $to
   * @return array
   */
  public function findByPeriod(\DateTime $from, \DateTime $to) {
    $to->modify('+1 day');

    $qb = $this->createQueryBuilder('rd')
      ->select('rd');
    $qb->leftJoin('rd.requirement', 'r');
    $qb->leftJoin('rd.assignment', 'a');
    $qb->leftJoin('rd.parent_item', 'pc');
    $qb->where('r.date >= ?1');
    $qb->andWhere('r.date < ?2');
    $qb->orderBy('pc.name', 'ASC');
    $qb->addOrderBy('a.date', 'ASC');
    $qb->addOrderBy('r.date', 'ASC');

    $qb->setParameters(array(
      1 => $from,
      2 => $to
    ));

    return $qb->getQuery()->getResult();
  }

}